package com.tinygray.productConsumer;

/**
 * @Author: tinygray
 * @Description: 公众号:Madison龙少，关注我你会越来越优秀。
 * @className: productConsumer_condition
 * @create: 2021-05-09 16:32
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 精确唤醒 condition
 */
public class productConsumer_condition {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareResource.print01();
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareResource.print02();
            }
        },"BB").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareResource.print03();
            }
        },"CC").start();
    }
}
class ShareResource {
    private int number = 1;//A:1 B:2 C:3
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    public void print01() {
        lock.lock();
        try {
            //判断
            while (number != 1) {
                condition1.await();
            }
            //干活
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            number = 2;
            //通知
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void print02() {
        lock.lock();
        try {
            //判断
            while (number != 2) {
                //等待
                condition2.await();
            }
            for (int i = 0; i <10 ; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //操作
            number = 3;
            //唤醒线程
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void print03() {
        lock.lock();
        try {
            //判断
            while (number != 3) {
                //等待
                condition3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //操作
            number = 1;
            //唤醒线程
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
